<?php

/**
 * This is the model class for table "friendship".
 *
 * The followings are the available columns in table 'friendship':
 * @property integer $id
 * @property integer $user_id
 * @property integer $friend_id
 * @property string $status
 *
 * The followings are the available model relations:
 * @property User $friend
 * @property User $user
 */
class Friendship extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'friendship';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_id, friend_id', 'required'),
			array('user_id, friend_id', 'numerical', 'integerOnly'=>true),
			array('status', 'length', 'max'=>32),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, user_id, friend_id, status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'friend' => array(self::BELONGS_TO, 'User', 'friend_id'),
			'user' => array(self::BELONGS_TO, 'User', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'user_id' => 'User',
			'friend_id' => 'Friend',
			'status' => 'Status',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('friend_id',$this->friend_id);
		$criteria->compare('status',$this->status,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Friendship the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function add()
	{
		$this->attributes=$_POST['Friendship'];
		return $this->save();
	}

	public function getFriend($user_id)
	{
		$data = $this->findAllByAttributes(
			array('user_id'=>$user_id,'status'=>'friend')
			);
		return $data;
	}

	public function getFriend6($user_id)
	{
		$Criteria = new CDbCriteria();
		$Criteria->condition = "user_id = $user_id AND status = ".'"friend"';
		$Criteria->limit = 6;
		$data = $this->findAll($Criteria);
		return $data;
	}

	public function remove($user_id,$friend_id)
	{
		//return $this->deleteByPk($friend_id);
	}

	public function sendRequest($user_id,$friend_id)
	{
		$sql = 'INSERT INTO `friendship`(`user_id`, `friend_id`, `status`) VALUES ('.$user_id.','.$friend_id.',"request(0)");';
		$query=Yii::app()->db->createCommand($sql)->execute();
		return $query;
	}

	public function acceptRequest($user_id,$friend_id)
	{
		$sql1 = 'UPDATE `friendship` SET `status`="friend" WHERE `user_id`='.$friend_id.' AND `friend_id`='.$user_id;
		$sql2 = 'INSERT INTO `friendship`(`user_id`, `friend_id`, `status`) VALUES ('.$user_id.','.$friend_id.',"friend");';

		$query=Yii::app()->db->createCommand($sql1)->execute();
		if($query == 0){
			return false;
		}else{
			$query=Yii::app()->db->createCommand($sql2)->execute();
			if($query == 0){
				return false;
			}else{
				return true;
			}
		}
	}

	public function denyRequest($user_id,$friend_id)
	{
		$sql = 'DELETE FROM `friendship` WHERE `user_id`='.$friend_id.' AND `friend_id`='.$user_id;
		$query=Yii::app()->db->createCommand($sql)->execute();
		return $query;
	}

	public function unfriend($user_id,$friend_id)
	{
		$sql1 = 'DELETE FROM `friendship` WHERE `user_id`='.$user_id.' AND `friend_id`='.$friend_id;
		$sql2 = 'DELETE FROM `friendship` WHERE `user_id`='.$friend_id.' AND `friend_id`='.$user_id;

		$query=Yii::app()->db->createCommand($sql1)->execute();
		if($query == 0){
			return false;
		}else{
			$query=Yii::app()->db->createCommand($sql2)->execute();
			if($query == 0){
				return false;
			}else{
				return true;
			}
		}
	}

	public function isFriend($user_id,$friend_id)
	{
		$data = $this->findByAttributes(
			array('user_id'=>$user_id,'friend_id'=>$friend_id)
			);
		if(isset($data->attributes))
		{
			$attributes = $data->attributes;
			if($attributes['status'] == 'friend')
				return true;
			else
				return false;
		}
		else
			return false;
	}

	public function friends($user_id)
	{
		$sql='
			SELECT
			friendship.id,
			friendship.user_id,
			COUNT(friendship.friend_id) As friends
			FROM
			friendship
			WHERE
			friendship.friend_id in (SELECT friendship.friend_id FROM friendship WHERE friendship.user_id = '.$user_id.' AND friendship.`status` = "friend") AND
			friendship.user_id != '.$user_id.' AND
			friendship.user_id not in (SELECT friendship.friend_id FROM friendship WHERE friendship.user_id = '.$user_id.' AND friendship.`status` = "friend")
			GROUP BY friendship.user_id
			ORDER BY friends DESC
			LIMIT 0,3';
		$query=Yii::app()->db->createCommand($sql)->queryAll();
		return $query;
	}

	public function viewListNotification($user_id,$limit,$page=1)
	{
		$Criteria = new CDbCriteria();
		$Criteria->condition = "friend_id = $user_id AND status like ".'"request%"';
		$Criteria->limit = $limit;
		$Criteria->order = 'id DESC';
		$Criteria->offset = ($page -1)*$limit;
		$data = $this->findAll($Criteria);
		return $data;
	}

	public function allRead($user_id)
	{
		$sql = 'UPDATE `friendship` SET `status`="request(1)" WHERE `friend_id` = '.$user_id.' AND `status` = "request(0)"';
		$query=Yii::app()->db->createCommand($sql)->execute();
		return $query;
	}

	public function getQuantityUnread($user_id)
	{
		$sql='
			SELECT
				COUNT(status) As quantityUnread
			FROM
				friendship
			WHERE
				friend_id = '.$user_id.'
			AND status = "request(0)"';
		$query=Yii::app()->db->createCommand($sql)->queryRow();
		return $query;
	}

	public function getRelation($user_id,$friend_id)
	{
		$sql="
			SELECT
				`user_id`,`friend_id`,`status`
			FROM
				friendship
			WHERE
				(`user_id` = $user_id AND
				`friend_id` = $friend_id )
			OR
				(`user_id` = $friend_id AND
				`friend_id` = $user_id)
			LIMIT 0,1";
		$query=Yii::app()->db->createCommand($sql)->queryRow();
		return $query;
	}

	public function getQuantitySameFriend($user_id,$friend_id)
	{
		$sql="
			SELECT
			COUNT(friendship.friend_id) As friends
			FROM
				friendship
			WHERE
				user_id = $user_id
				AND
				friendship.friend_id in (SELECT friendship.friend_id FROM friendship WHERE user_id = $friend_id);";
		$query=Yii::app()->db->createCommand($sql)->queryRow();
		return $query;
	}
}
